package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.utils.common.AppJwtUtil;
import com.sun.corba.se.spi.orbutil.threadpool.WorkQueue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author 一叠温酒
 */
@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.用户登录
        if (StringUtils.isNotEmpty(loginDto.getPhone())
                &&StringUtils.isNotEmpty(loginDto.getPassword()))
        {
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            String qwl = loginDto.getPassword()+apUser.getSalt();
            boolean equals = DigestUtils.md5DigestAsHex(qwl.getBytes()).equals(apUser.getPassword());
            if (equals)
            {
                String token = AppJwtUtil.getToken((long) apUser.getId());
                apUser.setPassword("");
                apUser.setSalt("");
                Map<String,Object> result = new HashMap<>();
                result.put("user",apUser);
                result.put("token",token);
                return ResponseResult.okResult(result);
            }else
            {
                return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

        }else
        {
            //2.游客登录
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> result = new HashMap<>();
            result.put("token",token);
            return ResponseResult.okResult(result);
        }
    }
}
